package com.ruoyi.develop.goodsOrderIn.controller;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysArea;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.constants.BusinessConstants;
import com.ruoyi.develop.goodsSale.domain.GoodsSale;
import com.ruoyi.develop.orderIronDetail.domain.OrderIronDetail;
import com.ruoyi.export.service.IExportService;
import com.ruoyi.system.service.ISysAreaService;
import com.ruoyi.utils.ExcelExport;
import org.apache.commons.collections.map.HashedMap;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.develop.goodsOrderIn.domain.GoodsOrderIn;
import com.ruoyi.develop.goodsOrderIn.service.IGoodsOrderInService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 入库信息管理Controller
 *
 * @author qh
 * @date 2023-01-05
 */
@RestController
@RequestMapping("/goodsOrderIn/goodsOrderIn")
public class GoodsOrderInController extends BaseController {
    @Autowired
    private IGoodsOrderInService goodsOrderInService;
    @Autowired
    private IExportService exportService;
    @Autowired
    private ISysAreaService areaService;

    /**
     * 查询入库信息管理列表
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsOrderIn:query')")
    @GetMapping("/list")
    public TableDataInfo list(GoodsOrderIn entity) {
        startPage();
        List<GoodsOrderIn> list = goodsOrderInService.selectList(entity);
        return getDataTable(list);
    }

    /**
     * 缓存里面查询
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsOrderIn:query')")
    @GetMapping("/listCache")
    public TableDataInfo listCache(GoodsOrderIn entity) {
        List<GoodsOrderIn> list = goodsOrderInService.selectListCache(entity);
        return getDataTable(list);
    }

    @GetMapping("/listOptions")
    public TableDataInfo listOptions(GoodsOrderIn entity) {
        List<GoodsOrderIn> list = goodsOrderInService.selectListCache(entity);
        return getDataTable(list);
    }

    @PreAuthorize("@ss.hasPermi('develop:GoodsOrderIn:query')")
    @GetMapping("/assessList")
    public TableDataInfo assessList(GoodsOrderIn entity) {
        startPage();
        List<GoodsOrderIn> list = goodsOrderInService.selectAssessList(entity);
        return getDataTable(list);
    }


    @GetMapping("/listBatch/{ids}")
    public TableDataInfo listBatch(@PathVariable("ids") String[] ids) {
//        startPage();
        List<GoodsOrderIn> list = goodsOrderInService.listBatch(ids);

        return getDataTable(list);
    }

    @Log(title = "仓库产品信息导出", businessType = BusinessType.EXPORT)
    @GetMapping("/exportGoodsInfo")
    public AjaxResult export(GoodsOrderIn entity, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        String date = DateUtils.getTime();//默认当天
        startPage();
        List<GoodsOrderIn> list = goodsOrderInService.selectList(entity);
        list.stream().forEach(e->{
            Map<String, Object> map = new HashMap<String, Object>();
//            map.put("fundCallback", DictUtils.getDictLabel(BusinessConstants.FUND_CALLBACK, e.getFundCallback()));
            e.setParams(map);
        });
        params.put("list", list);
        params.put("date", date);
        String fileName = request.getParameter("fileName");
        if(StringUtils.isBlank(fileName)){
            fileName = "仓库产品信息.xlsx";
        }
        String templateName = "仓库产品信息.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
        return null;
    }

    @Log(title = "商品入库信息导出 ", businessType = BusinessType.EXPORT)
    @GetMapping("/exportNormal")
    public void exportNormal(GoodsOrderIn entity, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        List<GoodsOrderIn> list = goodsOrderInService.selectList(entity);
        list.stream().forEach(item->{
            Map<String, Object> entityParams = new HashedMap();
            if(StringUtils.isNotBlank(item.getBuyType())){
                item.setBuyType(DictUtils.getDictLabel("buy_type", item.getBuyType()));
            }
            if(StringUtils.isNotBlank(item.getReimburse())){
                item.setReimburse(DictUtils.getDictLabel("yes_no", item.getReimburse()));
            }
            if(item.getBuyDate() != null){
                entityParams.put("buyDate", DateUtils.formatDate(item.getBuyDate(), "yyyy-MM-dd"));
            }
            if(item.getValidityTerm() != null){
                entityParams.put("validityTerm", DateUtils.formatDate(item.getValidityTerm(), "yyyy-MM-dd"));
            }
            item.setParams(entityParams);
        });
        params.put("list", list);
        params.put("nowDate", DateUtils.formatDate(new Date(), "yyyy年MM月dd日 HH时mm分"));
        // 设置强制下载不打开
        response.setContentType("application/force-download");
        String fileName = "商品入库信息清单.xlsx";
        String templateName = "商品入库信息清单.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
    }

    @Log(title = "商品库存信息导出 ", businessType = BusinessType.EXPORT)
    @GetMapping("/exportKc")
    public void exportKc(GoodsOrderIn entity, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> params = new HashMap<>();
        List<GoodsOrderIn> list = goodsOrderInService.selectList(entity);
        list.stream().forEach(item->{
            Map<String, Object> entityParams = new HashedMap();
            if(StringUtils.isNotBlank(item.getBuyType())){
                item.setBuyType(DictUtils.getDictLabel("buy_type", item.getBuyType()));
            }
            if(StringUtils.isNotBlank(item.getReimburse())){
                item.setReimburse(DictUtils.getDictLabel("yes_no", item.getReimburse()));
            }
            if(item.getBuyDate() != null){
                entityParams.put("buyDate", DateUtils.formatDate(item.getBuyDate(), "yyyy-MM-dd"));
            }
            if(item.getValidityTerm() != null){
                entityParams.put("validityTerm", DateUtils.formatDate(item.getValidityTerm(), "yyyy-MM-dd"));
            }
            item.setParams(entityParams);
        });
        params.put("list", list);
        params.put("nowDate", DateUtils.formatDate(new Date(), "yyyy年MM月dd日 HH时mm分"));
        // 设置强制下载不打开
        response.setContentType("application/force-download");
        String fileName = "商品库存信息清单.xlsx";
        String templateName = "商品库存信息清单.xlsx";
        exportService.baseXlsxExport(fileName, params, templateName, request, response);
    }
    /**
     * 获取入库信息管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsOrderIn:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return AjaxResult.success(goodsOrderInService.selectById(id));
    }

    /**
     * 新增入库信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsOrderIn:add')")
    @Log(title = "入库信息管理", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult add(@RequestBody GoodsOrderIn entity) {
        // 先查询编码是否存在
        GoodsOrderIn goodsOrderIn =  goodsOrderInService.selectByCodeAll(entity.getCode());
        if(goodsOrderIn != null){
            return AjaxResult.error("该产品编码已存在");
        }
        return toAjax(goodsOrderInService.insert(entity));
    }

    /**
     * 修改入库信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsOrderIn:edit')")
    @Log(title = "入库信息管理", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody GoodsOrderIn entity) {
        return toAjax(goodsOrderInService.update(entity));
    }

    @Log(title = "修改产品费用", businessType = BusinessType.UPDATE)
    @PutMapping("/editFee")
    public AjaxResult editFee(@RequestBody GoodsOrderIn entity) {
        return toAjax(goodsOrderInService.editFee(entity));
    }

    /**
     * 入库信息审核
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsOrderIn:assess')")
    @Log(title = "入库信息审核", businessType = BusinessType.UPDATE)
    @PutMapping("/assess")
    public AjaxResult assess(@RequestBody GoodsOrderIn entity) {
        if(StringUtils.isNotBlank(entity.getAssessStatus()) && entity.getAssessStatus().equals(BusinessConstants.ASSESS_STATUS_PASS)){
            entity.setDelFlag("0");
        }
        return toAjax(goodsOrderInService.update(entity));
    }

    @Log(title = "修改入库信息管理", businessType = BusinessType.UPDATE)
    @PutMapping("/editUpdate")
    public AjaxResult editUpdate(@RequestBody GoodsOrderIn entity) {
        GoodsOrderIn old=goodsOrderInService.selectById(entity.getId());
        SysArea sysArea = areaService.selectAreaById(entity.getDeptId());
        if(sysArea!=null){
            entity.setRemainderCount(entity.getCount().subtract(old.getCount()).add(old.getRemainderCount()));
            entity.setShengyu(entity.getRemainderCount().multiply(entity.getCostPrice()));
            goodsOrderInService.update(entity);
            if(entity.getCount()!=null && !entity.getCount().equals(BigDecimal.ZERO)){
                sysArea.setCounts(sysArea.getCounts().subtract(old.getCount()).add(entity.getCount()));
                sysArea.setShengyu(sysArea.getShengyu().subtract(old.getRemainderCount()).add(entity.getRemainderCount()));
            }
            if(entity.getCostTax()!=null && !entity.getCostTax().equals(BigDecimal.ZERO)){
                sysArea.setTaxprice(sysArea.getTaxprice().subtract(old.getCostTax()).add(entity.getCostTax()));
                sysArea.setAllmaoney(sysArea.getAllmaoney().subtract(old.getCostTax()).add(entity.getCostTax()));
            }
            if(entity.getDun()!=null && !entity.getDun().equals(BigDecimal.ZERO)){
                sysArea.setAlldun(sysArea.getAlldun().subtract(old.getDun()).add(entity.getDun()));
                sysArea.setShengdun(sysArea.getShengdun().subtract(old.getDun()).add(entity.getDun()));
            }
            return toAjax(areaService.updateArea(sysArea));
        }
        return toAjax(goodsOrderInService.update(entity));
    }

    @PutMapping("/editForImburseId")
    public AjaxResult editForImburseId(@RequestBody GoodsOrderIn entity) {
        return toAjax(goodsOrderInService.updateForImburseId(entity));
    }

    /**
     * 删除入库信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsOrderIn:remove')")
    @Log(title = "入库信息管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(goodsOrderInService.deleteByIds(ids));
    }

    @PreAuthorize("@ss.hasPermi('develop:GoodsOrderIn:remove')")
    @Log(title = "删除入库信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/deleted/{id}")
    public AjaxResult deleted(@PathVariable String id) {
        GoodsOrderIn entity=goodsOrderInService.selectById(id);
        SysArea sysArea=areaService.selectAreaById( entity.getDeptId());
        if(sysArea!=null){
            if(entity.getCount()!=null && !entity.getCount().equals(BigDecimal.ZERO)){
                sysArea.setCounts(sysArea.getCounts().subtract(entity.getCount()));
                sysArea.setShengyu(sysArea.getShengyu().subtract(entity.getCount()));
            }
            if(entity.getCostTax()!=null && !entity.getCostTax().equals(BigDecimal.ZERO)){
                sysArea.setTaxprice(sysArea.getTaxprice().subtract(entity.getCostTax()));
                sysArea.setAllmaoney(sysArea.getAllmaoney().subtract(entity.getCostTax()));
            }
            if(entity.getDun()!=null && !entity.getDun().equals(BigDecimal.ZERO)){
                sysArea.setAlldun(sysArea.getAlldun().subtract(entity.getDun()));
                sysArea.setShengdun(sysArea.getShengdun().subtract(entity.getDun()));
            }
            areaService.updateArea(sysArea);
        }
        return toAjax(goodsOrderInService.deleteById(id));
    }

    @GetMapping(value = "/initOrderInDicts")
    public AjaxResult initOrderInDicts() {
        List<SysDictData> nameList = goodsOrderInService.selectAllGoodsNames();
        List<SysDictData> brandList = goodsOrderInService.selectAllGoodsBrands();
        Map<String, Object> retMap = new HashedMap();
        retMap.put("nameList", nameList);
        retMap.put("brandList", brandList);
        return AjaxResult.success(retMap);
    }

    @PreAuthorize("@ss.hasPermi('develop:GoodsOrderIn:add')")
    @Log(title = "入库信息管理", businessType = BusinessType.INSERT)
    @PostMapping("/addIn")
    public AjaxResult addIn(@RequestBody GoodsOrderIn entity) {
        return toAjax(goodsOrderInService.insertIn(entity));
    }

    @PostMapping("/insertOrderUpdateArea")
    public AjaxResult insertOrderUpdateArea(@RequestBody GoodsOrderIn entity) {
        return toAjax(goodsOrderInService.insertOrderUpdateArea(entity));
    }
    /**
     * 修改入库信息管理
     */
    @PreAuthorize("@ss.hasPermi('develop:GoodsOrderIn:edit')")
    @Log(title = "入库信息管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateIn")
    public AjaxResult updateIn(@RequestBody GoodsOrderIn entity) {
        return toAjax(goodsOrderInService.updateIn(entity));
    }

    @Log(title = "导入数据", businessType = BusinessType.INSERT)
    @PostMapping("/import")
    public AjaxResult importData(GoodsOrderIn entity, MultipartFile file) {
        Map<String, Object> error = new HashMap<>();
        error = goodsOrderInService.importData(entity,file);
        error.put("code", 200);
        return AjaxResult.success(error);
    }

    /**
     * 根据 大类别获取编号
     */
    @GetMapping(value = "/getGoodsCodeByArea")
    public AjaxResult getGoodsCodeByArea(GoodsOrderIn entity) {
        Map<String,Object> returnMap = new HashMap<>();
        String codeMax = goodsOrderInService.getGoodsCodeByArea(entity);
        returnMap.put("code",codeMax);
        return AjaxResult.success(returnMap);
    }


}
